package com.example.JavaWebApi.core.controlleradvice;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.JavaWebApi.core.commonmodel.PageModel;
import com.example.JavaWebApi.core.commonmodel.ResponseModel;
import com.example.JavaWebApi.core.controlleradvice.annotation.IgnoreDataPacking;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * @program: java-web-api
 * @description: 结果包装
 * @author: 杨泽
 * @create: 2022-10-09 16:33
 */
@RestControllerAdvice(basePackages = "com.example.JavaWebApi.controller")
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return !(returnType.getParameterType().isAssignableFrom(ResponseModel.class)||returnType.hasMethodAnnotation(IgnoreDataPacking.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(returnType.getParameterType().equals(String.class)){
            ObjectMapper mapper=new ObjectMapper();
            try {
                return mapper.writeValueAsString(new ResponseModel<>(body));
            } catch (JsonProcessingException e) {
                throw new Error("结果包装失败！");
            }
        }
        else if(returnType.getParameterType().isAssignableFrom(Page.class)){
            PageModel<?> pageModel=new PageModel<>((IPage<?>)body);
            return new ResponseModel<>(pageModel);
        }
        else {
            return new ResponseModel<>(body);
        }
    }
}